package day_2022_4_to_7.day48;

import java.util.Arrays;

/**
 * 微信红包
 * @author haomin
 * @date 2022/05/21 08:48
 **/
public class Day23_1_FindHalfValue {
    // 方法一：
    public int getValue(int[] gifts, int n) {
        Arrays.sort(gifts);
        int result = gifts[n/2];
        int count = 0;
        for(int i = 0;i < n;i++){
            if(result == gifts[i]){
                count++;
            }
        }
        if(count > n/2){
            return result;
        }else{
            return 0;
        }
    }

    // 方法二：
//    public int getValue2(int[] gifts, int n) {
//        // Map
//    }

    // 方法三：
    public int getValue3(int[] gifts, int n) {
        int target = gifts[0];
        int times = 1;
        for (int i = 1; i < n; i++) {
            if(times < 0){
                target = gifts[i];
            }else if(target == gifts[i]){
                times++;
            }else if(target != gifts[i]){
                times--;
            }
        }
        times = 0;
        for (int i = 0; i < n; i++) {
            if(target == gifts[i]){
                times++;
            }
        }
        if(times > n/2){
            return target;
        }else {
            return 0;
        }
    }
}